package com.ouc.eddyAlgorithm.utils;

import com.ouc.common.utils.DateUtils;
import com.ouc.common.utils.ProgramUtil;
import com.ouc.common.utils.StringUtils;
import com.ouc.common.utils.SystemUtils;
import com.ouc.common.utils.file.FileUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

/**
 * @author B504
 * @date 2023/2/4
 * @apiNote
 */

/**
 * python相关工具
 *
 * @author MY-PC
 */
@Slf4j
public class PythonUtil {
  /**
   * 对ERA5的nc数据通过Java调用Python来进行下载
   *
   * @param pythonPath Python文件路径
   * @param dateTime   时间
   * @param above      nc文件上边界
   * @param left       nc文件左边界
   * @param down       nc文件下边界
   * @param right      nc文件右边界
   * @param outPath    nc文件下载路径
   * @param variables  下载的变量字符串
   * @return
   */
  public static Boolean startPythonOfDownload(String pythonPath, Date dateTime, String above, String left, String down, String right, String outPath, String variables) {
    try {
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(dateTime);
      String year = String.valueOf(calendar.get(Calendar.YEAR));
      String month = String.valueOf(calendar.get(Calendar.MONTH) + 1);
      String days = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
      String time = StringUtils.padl(calendar.get(Calendar.HOUR_OF_DAY), 2) + ":00";
      //String[] split = dateTime.split("-");
      //  各种参数
      String header = "cmd /c ";
      year = " --aa " + year;
      month = " --bb " + month;
      days = " --cc " + days;
      time = " --dd " + time;
      above = " --ee " + above;
      left = " --ff " + left;
      down = " --gg " + down;
      right = " --hh " + right;
      outPath = " --ii " + outPath;
      variables = " --jj " + variables;
      String argsParm = year + month + days + time + above + left + down + right + outPath + variables;
      String sb = header + pythonPath.charAt(0) + ":" + " & " +
          "cd " + new File(pythonPath).getParent() + " & " +
          FileUtils.getName(pythonPath) + argsParm;
      Process pro = Runtime.getRuntime().exec(sb);
      ProgramUtil.errorMessage(pro);
      ProgramUtil.infoMessage(pro);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * sar数据的自动下载工具
   * 调用Python程序
   *
   * @param pythonPath python程序地址
   * @param dateTime   时间
   * @param startLon   开始经度
   * @param endLon     结束经度
   * @param startLat   开始纬度
   * @param endLat     结束纬度
   * @param outPath    下载路径
   * @return
   */
  public static Boolean startPythonOfDownloadFromSAR(String pythonPath, Date dateTime, String startLon, String endLon, String startLat, String endLat, String outPath) {
    try {
      return startPythonOfDownloadFromSAR(pythonPath, dateTime, dateTime, startLon, endLon, startLat, endLat, outPath);
      /*Calendar calendar = Calendar.getInstance();
      calendar.setTime(dateTime);
      String s = DateUtils.parseDateToStr("yyyy-MM-dd", dateTime);
      String startTime = s + "T00:00:00UTC";
      String endTime = s + "T23:59:59UTC";
      String polygon = String.format("POLYGON((%s@%s,%s@%s,%s@%s,%s@%s,%s@%s))", startLon, startLat, endLon, startLat, endLon, endLat, startLon, endLat, startLon, startLat);
      //  各种参数
      String header = "cmd /c ";
      startTime = " --aa " + startTime;
      endTime = " --bb " + endTime;
      polygon = " --cc " + polygon;
      outPath = " --dd " + outPath;
      String argsPram = startTime + endTime + polygon + outPath;
      String sb = header + pythonPath.charAt(0) + ":" + " & " +
          "cd " + new File(pythonPath).getParent() + " & " +
          FileUtils.getName(pythonPath) + argsPram;
      Process pro = Runtime.getRuntime().exec(sb);
      //ProgramUtil.errorMessage(pro);
      ProgramUtil.infoMessage(pro);
      return true;*/
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  public static Boolean startPythonOfDownloadFromSAR(String pythonPath, Date startDate, Date endDate, String startLon, String endLon, String startLat, String endLat, String outPath) {
    try {
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(startDate);
      String s = DateUtils.parseDateToStr("yyyy-MM-dd", startDate);
      String s2 = DateUtils.parseDateToStr("yyyy-MM-dd", endDate);
      String startTime = s + "T00:00:00UTC";
      String endTime = s2 + "T23:59:59UTC";
      String polygon = String.format("POLYGON((%s@%s,%s@%s,%s@%s,%s@%s,%s@%s))", startLon, startLat, endLon, startLat, endLon, endLat, startLon, endLat, startLon, startLat);
      //  各种参数
//      startTime = " --aa " + startTime;
//      endTime = " --bb " + endTime;
//      polygon = " --cc " + polygon;
//      outPath = " --dd " + outPath;
//      String argsPram = startTime + endTime + polygon + outPath;
      Process pro = null;
      if (!new File(outPath).exists()) {
        new File(outPath).mkdirs();
      }
      String dirName = DateUtils.parseDateToStr("yyyyMMdd", startDate);
      String destPath = outPath + File.separator + dirName;
      if (!new File(destPath).exists()) {
        new File(destPath).mkdirs();
      }
      String pythonDestPath = destPath + File.separator + FileUtils.getName(pythonPath);
      if (!new File(pythonDestPath).exists()) {
        Files.copy(new File(pythonPath).toPath(), new File(pythonDestPath).toPath());
      }
      if (SystemUtils.isWindows()) {

        String header = "cmd /c ";
        String startTime1 = " --aa " + startTime;
        String endTime1 = " --bb " + endTime;
        String polygon1 = " --cc " + polygon;
        String outPath1 = " --dd " + outPath;
        String argsPram = startTime1 + endTime1 + polygon1 + outPath1;
        pythonPath = pythonDestPath;
        log.info("your pythonPath is:" + pythonPath);
        String sb = header + pythonPath.charAt(0) + ":" + " & " +
            "cd " + new File(pythonPath).getParent() + " & " + "python " +
            FileUtils.getName(pythonPath) + argsPram;
        pro = Runtime.getRuntime().exec(sb);
        ProgramUtil.infoMessage(pro);
      } else {
        pythonPath = pythonDestPath;
        log.info("your pythonPath is:" + pythonPath);
        String[] cmd;
        outPath = destPath + File.separator;
        //cmd = new String[]{"/bin/bash", "-c", "cd " + new File(pythonPath).getParent() + " && python3 " + pythonPath + " --aa " + startTime + " --bb " + endTime + " --cc \"POLYGON\\(\\(105@145,0@145,0@50,105@50,105@145\\)\\)\" --dd " + outPath};
        //cmd = new String[]{"/bin/bash", "-c", "cd " + new File(pythonPath).getParent() + " && python3 " + pythonPath + " --aa " + startTime + " --bb " + endTime + " --cc \"" + polygon.replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)") + "\" --dd " + outPath};
        // cmd = new String[]{"gnome-terminal", "--working-directory=" + new File(pythonPath).getParent(), "-e", "/bin/bash -c 'python3 " + pythonPath + " --aa " + startTime + " --bb " + endTime + " --cc "" + polygon.replaceAll("\(", "\\(").replaceAll("\)", "\\)") + "" --dd " + outPath + "; exec /bin/bash -i'"};
        cmd = new String[]{"/bin/bash", "-c", "cd " + new File(pythonPath).getParent() + " && python3 " + pythonPath + " --aa " + startTime + " --bb " + endTime + " --cc \"" + polygon + "\" --dd " + outPath};
        Process process = Runtime.getRuntime().exec(cmd);
        StringBuilder sb = new StringBuilder();
        for (String s1 : cmd) {
          sb.append(s1);
        }
        log.info("stringbuilder is" + sb.toString());

        //cmd = new String[]{"/bin/bash", "-c", "cd " + new File(pythonPath).getParent(), "&&", "python3", pythonPath, "--aa", startTime, "--bb", endTime, "--cc", polygon, "--dd", outPath};
        log.info("your cmd Array path is:" + Arrays.toString(cmd));
        log.info("your cmd python path is:" + new File(pythonPath).getParent());

        pro = Runtime.getRuntime().exec(cmd);
        ProgramUtil.infoMessage(pro);
      }
//      ProgramUtil.errorMessage(pro);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * 调用深度学习gedyolo方法
   * 获取涡旋的txt
   *
   * @param pythonFilePath python文件
   * @param ncFilePath     nc文件
   * @param startLon       开始经度
   * @param endLon         结束经度
   * @param startLat       开始维度
   * @param endLat         结束纬度
   * @param confidence     置信度
   * @param nmsIou         非极大抑制
   * @return
   */
  public static Boolean startGedYolo(String pythonFilePath, String ncFilePath, String startLon, String endLon, String startLat, String endLat, String confidence, String nmsIou) {
    try {
      //  各种参数
      String header = "cmd /c ";
      StringBuilder sb = new StringBuilder();
      ncFilePath = " --aa " + ncFilePath;
      startLon = " --bb " + startLon;
      endLon = " --cc " + endLon;
      startLat = " --dd " + startLat;
      endLat = " --ee " + endLat;
      confidence = " --ff " + confidence;
      nmsIou = " --gg " + nmsIou;
      String argsPram = ncFilePath + startLon + endLon + startLat + endLat + confidence + nmsIou;
      sb.append(header).append(pythonFilePath.charAt(0)).append(":").append(" & ")
          .append("cd ").append(new File(pythonFilePath).getParent()).append(" & ")
          .append("activate yolo").append(" & ")
          .append("python ").append(FileUtils.getName(pythonFilePath))
          .append(argsPram);
      Process pro = Runtime.getRuntime().exec(sb.toString());
      ProgramUtil.errorMessage(pro);
      ProgramUtil.infoMessage(pro);

      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }

  }
}
